package service

import (
	"QHMedLink/model"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 1. 创建订单（事务处理）
func CreateOrder(db *gorm.DB, order *model.PointsOrder) error {
	return db.Transaction(func(tx *gorm.DB) error {
		// 使用唯一性约束防止重复订单
		return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(order).Error
	})
}

// 2. 按用户查询订单（分页）
func GetOrdersByUser(db *gorm.DB, userID uint, page, size int) ([]model.PointsOrder, error) {
	var orders []model.PointsOrder
	offset := (page - 1) * size
	query := db.Where("user_id = ?", userID).Offset(offset).Limit(size)
	if err := query.Order("order_time DESC").Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}

// 3. 更新支付状态（带版本控制）
func UpdatePaymentStatus(db *gorm.DB, orderID string, newStatus model.PaymentStatus) error {
	return db.Transaction(func(tx *gorm.DB) error {
		return tx.Model(&model.PointsOrder{}).
			Where("order_id = ? AND payment_status = ?", orderID, model.Pending).
			Update("payment_status", newStatus).Error
	})
}

// 4. 复合条件查询（状态+时间范围）
func GetOrdersByCondition(db *gorm.DB, status model.PaymentStatus, start, end time.Time) ([]model.PointsOrder, error) {
	var orders []model.PointsOrder
	query := db.Where("payment_status = ? AND order_time BETWEEN ? AND ?", status, start, end)
	if err := query.Find(&orders).Error; err != nil {
		return nil, err
	}
	return orders, nil
}

// 5. 删除订单（硬删除）
func DeleteOrder(db *gorm.DB, orderID string) error {
	return db.Model(&model.PointsOrder{}).
		Where("order_id = ?", orderID).
		Update("is_deleted", true).Error
}
